package com.example.xmhds_1.entity;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 群聊实体类
 */
@Data
@TableName("group_chat")
public class GroupChat {
    /**
     * 主键ID
     */
    @TableId(type = IdType.AUTO)
    private Long id;

    /**
     * 群ID
     */
    private String groupId;

    /**
     * 群名称
     */
    private String groupName;

    /**
     * 群成员列表，JSON数组格式
     */
    private String members;

    /**
     * 消息记录，JSON数组格式
     */
    private String messages;

    /**
     * 创建时间
     */
    private LocalDateTime createTime;

    /**
     * 更新时间
     */
    private LocalDateTime updateTime;

    /**
     * 逻辑删除标记
     */
    @TableLogic
    private Integer deleted;

    /**
     * 获取成员列表JSONArray
     */
    public JSONArray getMembers() {
        try {
            return JSON.parseArray(this.members);
        } catch (Exception e) {
            return new JSONArray();
        }
    }

    /**
     * 设置成员列表
     */
    public void setMembers(JSONArray members) {
        this.members = members.toJSONString();
    }

    /**
     * 获取消息列表JSONArray
     */
    public JSONArray getMessages() {
        try {
            return JSON.parseArray(this.messages);
        } catch (Exception e) {
            return new JSONArray();
        }
    }

    /**
     * 设置消息列表
     */
    public void setMessages(JSONArray messages) {
        this.messages = messages.toJSONString();
    }

    /**
     * 添加新成员
     */
    public void addMember(JSONObject member) {
        JSONArray members = getMembers();
        members.add(member);
        setMembers(members);
    }

    /**
     * 添加新消息
     */
    public void addMessage(JSONObject message) {
        JSONArray messages = getMessages();
        messages.add(message);
        setMessages(messages);
    }

    /**
     * 获取群成员信息
     */
    public JSONObject getMemberInfo(String userId) {
        JSONArray members = getMembers();
        for (int i = 0; i < members.size(); i++) {
            JSONObject member = members.getJSONObject(i);
            if (userId.equals(member.getString("userId"))) {
                return member;
            }
        }
        return null;
    }

    /**
     * 更新成员信息
     */
    public void updateMember(String userId, JSONObject newInfo) {
        JSONArray members = getMembers();
        for (int i = 0; i < members.size(); i++) {
            JSONObject member = members.getJSONObject(i);
            if (userId.equals(member.getString("userId"))) {
                members.set(i, newInfo);
                break;
            }
        }
        setMembers(members);
    }
}
